<template>
	<view>
	
	 <u-search
	 placeholder="请输入商品"
	 v-model="keyword" 
	 actionText="添加"
	 @custom="handleSearch"
	 @search="handleSearch"
	 ></u-search>
	 <view class="title">
		<view>商品</view>
		<view>操作</view>
	 </view>
	 <view v-for="item in list" :key="item.goods_id" class="content">
		<view class="item">{{item.goods_name}}</view>
		<view class="item">
			<u-number-box 
			:value="item.goods_count"
			@input="handleNumberInput($event,item.goods_id)"
			></u-number-box>
		</view>
	 </view>
	</view>
</template>

<script> 
	export default {
		data() {
			return {
				keyword:''
			}
		},
		methods:{
			handleSearch(){
				console.log('用户点击了搜索或者enter')
				const newList = [...this.list]
				const goodsObj = newList.find(v=> v.goods_name === this.keyword)
				if(goodsObj){
					//商品已存在
					goodsObj.goods_count++;
				}else{
					newList.push({
					goods_id:Date.now(),
					goods_name:this.keyword,
					goods_count:1
				})
				}
				
				this.$store.commit('setList',newList)

			},
			handleNumberInput(val,id){
				console.log(val)
				const newList = [...this.list]
				const obj = newList.find(v=>v.goods_id === id)
				if(obj){
					obj.goods_count = val
					this.$store.commit('setList',newList)
				}
			}
		},
		computed:{
			list(){
				return this.$store.state.list
			}
		}
		
	}
</script>

<style lang="scss">
.title,
.content{
	display: flex;
	.item{
		flex: 1;
		border: 1px solid #ddd;
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 20rpx;
	}
}
</style>
